package com.luoqiz.project.qq.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.UUID;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.luoqiz.project.qq.client.threads.ChatThread;


public class ChatJFrame extends JFrame {

	private static final long serialVersionUID = -5619976434808526751L;

	private Socket socket;
	private OutputStream out;
	public JTextArea msgContentJta;
	
	public ChatJFrame() {
		this.setTitle("客户端");
		this.setVisible(true);
		this.setLayout(null);
		this.setBounds(200, 200, 700, 500);
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					out.flush();
					out.close(); 
					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				System.exit(-1);
			}
		});
		init();
	}

	public void init() {
		//message history
		msgContentJta = new JTextArea();
		JScrollPane msgContentJsp = new JScrollPane(msgContentJta);
		msgContentJsp.setBounds(10, 10, 600, 300);
		this.add(msgContentJsp);

		//new message
		JTextArea sendMsgJta = new JTextArea();
		JScrollPane sendMsgJsp = new JScrollPane(sendMsgJta);
		sendMsgJsp.setBounds(10, 350, 400, 80);
		this.add(sendMsgJsp);

		//The button that sends the message
		JButton sendBtn = new JButton("发送");
		sendBtn.setBounds(450, 360, 100, 30);
		sendBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				//Get the message content
				String sendMsg = sendMsgJta.getText();
				try {
					//The output message
					out.write(sendMsg.getBytes());
					sendMsgJta.setText("");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});
		this.add(sendBtn);
		
		try {
			socket = new Socket(Constant.SERVER_IP, Constant.SERVER_PORT);
			out = socket.getOutputStream();
			
			//the socket id
			out.write(UUID.randomUUID().toString().getBytes());
			new ChatThread(this,socket).start();
		} catch (IOException  e) {
			e.printStackTrace();
		}

	}
}
